package com.feng.financial.manager.service;

import com.feng.financial.common.querydsl.FetchResponse;
import com.feng.financial.common.web.Range;
import com.feng.financial.manager.repository.ProductRepository;
import com.feng.financial.model.ProductEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * @author Administrator
 */
@Service
public class ProductService {

    @PersistenceContext
    private EntityManager em;

    @Autowired
    private ProductRepository productRepository;

    public ProductEntity findOne(String id){
        return em.find(ProductEntity.class,id);
    }

    public FetchResponse<ProductEntity> findAllByPage(Range range){
        Page<ProductEntity> page = productRepository.findAll(PageRequest.of(range.getPageNo(), range.getLength()));
        FetchResponse<ProductEntity> response = new FetchResponse<>();
        response.setData(page.getContent());
        response.setRows(page.getTotalElements());
        response.setStart(page.getPageable().getOffset());
        return response;
    }

    @Transactional
    public ProductEntity saveProduct(ProductEntity product){
        em.persist(product);
        return product;
    }

}
